# -*- coding: utf8 -*-

from HTMLParser import HTMLParser
from urllib import urlopen
import re


class DisciplinesList(HTMLParser):
    def __init__(self, url, charset='ISO-8859-1'):
        HTMLParser.__init__(self)
        self.CHARSET = charset
        page = urlopen(url)
        self.data = []
        self.evaluate_code = False
        self.evaluate_name = False
        self.current_code = None
        self.code_re = re.compile(r'[A-Z]{3}\d{5}')
        self.feed(page.read())

    def handle_starttag(self, tag, attrs):
        if tag == 'font' and attrs and self.current_code:
            for key, value in attrs:
                if key == 'class' and value == 'nomedisciplina':
                    self.evaluate_name = True
                    break

        if tag == 'td' and attrs and \
           not (self.evaluate_code or self.current_code):
            for key, value in attrs:
                if key == 'class' and value == 'conteudoTabelaCorForte':
                    self.evaluate_code = True
                    break

    def handle_data(self, data):
        if self.evaluate_code:
            text = unicode(data.strip(), self.CHARSET)
            if self.code_re.match(text):
                self.current_code = text
                self.evaluate_code = False

        if self.evaluate_name:
            self.data.append((self.current_code, unicode(data.strip(), self.CHARSET)))
            self.evaluate_name = False
            self.current_code = None
